// detail-driver.ts - 司机端任务详情页
interface TaskData {
  id: string
  type: string
  typeIcon: string
  typeName: string
  startLocation: string
  startAddress?: string
  endLocation: string
  endAddress?: string
  status: string
  statusText: string
  urgencyLevel: string
  urgencyText: string
  passengerCount: number
  createTime: string
  contactPhone: string
  patientCondition?: string
  orderType?: string
  distance: number
  duration: number
}

interface VehicleCheck {
  selected: string  // 选中的选项
  result: string    // 检查结果文字
}

interface PatientInfo {
  description: string
  images: string[]
  videos: string[]
}

Page({
  data: {
    taskId: '',
    statusBarHeight: '44px',
    taskData: null as TaskData | null,
    patientInfo: null as PatientInfo | null,
    showMap: false,
    currentLocation: null as any,
    mapMarkers: [] as any[],
    
    // 检查项
    vehicleCheck: { selected: '', result: '' } as VehicleCheck,
    safetyCheck: { selected: '', result: '' } as VehicleCheck,
    otherCheck: { selected: '', result: '' } as VehicleCheck
  },

  onLoad(options: any) {
    this.setStatusBarHeight()
    this.checkLogin()
    
    const { id } = options
    if (id) {
      this.setData({ taskId: id })
      this.loadTaskDetail()
    }
  },

  setStatusBarHeight() {
    const windowInfo = (wx as any).getWindowInfo()
    const statusBarHeight = windowInfo.statusBarHeight || 44
    this.setData({
      statusBarHeight: statusBarHeight + 'px'
    })
  },

  checkLogin() {
    const userRole = wx.getStorageSync('userRole')
    if (userRole !== 'driver') {
      wx.reLaunch({ url: '/pages/login/login' })
    }
  },

  goBack() {
    wx.navigateBack()
  },

  loadTaskDetail() {
    wx.showLoading({ title: '加载中...' })
    
    setTimeout(() => {
      // 模拟数据，可以通过URL参数 status=pending 或 status=in_progress 来测试不同状态
      const urlStatus = this.data.taskId.includes('pending') ? 'pending' : 'in_progress'
      
      const mockData: TaskData = {
        id: this.data.taskId,
        type: 'ambulance',
        typeIcon: '🚑',
        typeName: '救护车',
        startLocation: '辽宁省-沈阳市',
        startAddress: '某某东大街112号院东恒生宇楼B座11.5',
        endLocation: '北京市-东城区',
        endAddress: '协和医院本部',
        status: urlStatus,
        statusText: urlStatus === 'pending' ? '待发车' : '待发车',
        urgencyLevel: 'low',
        urgencyText: '低',
        passengerCount: 2,
        createTime: '2025-09-07 周日 09:22',
        contactPhone: '135 0000 0000',
        patientCondition: '123',
        orderType: '本人下单',
        distance: 520,
        duration: 480
      }
      
      // 如果是已发车状态，设置检查结果
      const vehicleCheck = urlStatus === 'in_progress' ? { selected: 'option1', result: '文字' } : { selected: '', result: '' }
      const safetyCheck = urlStatus === 'in_progress' ? { selected: 'option1', result: '文字' } : { selected: '', result: '' }
      const otherCheck = urlStatus === 'in_progress' ? { selected: 'option1', result: '文字' } : { selected: '', result: '' }
      
      const patientInfo: PatientInfo = {
        description: '患者男性，65岁，突发胸痛伴呼吸困难约2小时，既往有高血压病史10年，规律服药控制。目前意识清楚，面色苍白，出汗较多。',
        images: [
          'https://picsum.photos/400/400?random=3',
          'https://picsum.photos/400/400?random=4'
        ],
        videos: []
      }
      
      this.setData({
        taskData: mockData,
        patientInfo: patientInfo,
        showMap: false,
        currentLocation: {
          latitude: 39.908823,
          longitude: 116.397470
        },
        vehicleCheck,
        safetyCheck,
        otherCheck
      })
      
      this.updateMapMarkers()
      wx.hideLoading()
    }, 800)
  },
  
  // 选择车况检查
  selectVehicleCheck(e: any) {
    const option = e.currentTarget.dataset.option
    this.setData({
      vehicleCheck: {
        selected: option,
        result: `选项${option.slice(-1)}`
      }
    })
  },
  
  // 选择安全检查
  selectSafetyCheck(e: any) {
    const option = e.currentTarget.dataset.option
    this.setData({
      safetyCheck: {
        selected: option,
        result: `选项${option.slice(-1)}`
      }
    })
  },
  
  // 选择其他选项
  selectOtherCheck(e: any) {
    const option = e.currentTarget.dataset.option
    this.setData({
      otherCheck: {
        selected: option,
        result: `选项${option.slice(-1)}`
      }
    })
  },
  
  // 确认订单（待发车状态）
  confirmOrder() {
    const { vehicleCheck, safetyCheck, otherCheck } = this.data
    
    if (!vehicleCheck.selected || !safetyCheck.selected || !otherCheck.selected) {
      wx.showToast({
        title: '请完成所有检查项',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认订单',
      content: '确认接受此订单并出发？',
      success: (res) => {
        if (res.confirm) {
          // 更新状态为进行中
          const taskData = this.data.taskData
          if (taskData) {
            taskData.status = 'in_progress'
            taskData.statusText = '待发车'
            this.setData({ taskData })
          }
          
          wx.showToast({
            title: '订单已确认',
            icon: 'success'
          })
        }
      }
    })
  },

  updateMapMarkers() {
    if (!this.data.currentLocation) return
    
    const markers = [{
      id: 1,
      latitude: this.data.currentLocation.latitude,
      longitude: this.data.currentLocation.longitude,
      width: 40,
      height: 40,
      label: {
        content: '🚑',
        fontSize: 24,
        color: '#FF5252',
        bgColor: '#ffffff',
        borderRadius: 20,
        padding: 5
      }
    }]
    
    this.setData({ mapMarkers: markers })
  },

  previewPatientImage(e: any) {
    const index = e.currentTarget.dataset.index
    const patientInfo = this.data.patientInfo
    const images = patientInfo && patientInfo.images ? patientInfo.images : []
    wx.previewImage({
      current: images[index],
      urls: images
    })
  },

  openNavigation() {
    const taskData = this.data.taskData
    if (!taskData) return

    wx.openLocation({
      latitude: 39.916423,
      longitude: 116.397079,
      name: taskData.endLocation,
      address: taskData.endAddress || taskData.endLocation,
      scale: 18
    })
  },

  updateLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          currentLocation: {
            latitude: res.latitude,
            longitude: res.longitude
          }
        })
        
        this.updateMapMarkers()
        
        wx.showToast({
          title: '位置已更新',
          icon: 'success'
        })
      },
      fail: () => {
        wx.showToast({
          title: '获取位置失败',
          icon: 'none'
        })
      }
    })
  },

  // 已到达
  arriveDestination() {
    wx.showModal({
      title: '确认到达',
      content: '确认已到达目的地？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '已到达目的地',
            icon: 'success'
          })
          setTimeout(() => wx.navigateBack(), 1500)
        }
      }
    })
  },

  showMore() {
    wx.showActionSheet({
      itemList: ['联系调度中心', '紧急求助'],
      success: (res) => {
        if (res.tapIndex === 0 || res.tapIndex === 1) {
          wx.makePhoneCall({ phoneNumber: '400-123-4567' })
        }
      }
    })
  }
})

